package com.mustafaiev.tair.cts.tapestry.pages.payers;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.mustafaiev.tair.cts.exeptions.DataNotRemovedException;
import com.mustafaiev.tair.cts.facade.IPayerFacade;
import com.mustafaiev.tair.cts.factory.ICostTrackingSystemFacadeFactory;
import com.mustafaiev.tair.cts.tapestry.dto.PayerDTO;

public class Index {

	@Inject
	private ICostTrackingSystemFacadeFactory facadeFactory;

	@InjectPage
	private Add add;

	@Property
	@Persist
	private List<PayerDTO> payers;

	@Property
	@Persist
	private List<PayerDTO> payersToDelete;

	@Property
	@Persist
	private PayerDTO payer;

	@Component(id = "payersForm")
	private Form form;

	@SetupRender
	void setupRender() {
		this.payersToDelete = new ArrayList<PayerDTO>();
		this.payers = this.facadeFactory.getFacade(IPayerFacade.class)
				.retrievePayers();
	}

	@OnEvent(value = "add")
	public Object addPayer() {
		return this.add;
	}

	public Object onSelectedFromTopDelete() {
		try {
			getFacade().deletePayers(this.payersToDelete);
		} catch (final DataNotRemovedException e) {
		}
		return null;
	}

	public Object onSelectedFromTopEdit() {
		return null;
	}

	public Object onSelectedFromBottomDelete() {
		try {
			getFacade().deletePayers(this.payersToDelete);
		} catch (final DataNotRemovedException e) {
		}
		return null;
	}

	public Object onSelectedFromBottomEdit() {
		return null;
	}

	public boolean isCheck() {
		return false;
	}

	public void setCheck(final boolean check) {
		if (check) {
			this.payersToDelete.add(this.payer);
		}
	}

	private IPayerFacade getFacade() {
		final IPayerFacade facade = this.facadeFactory
				.getFacade(IPayerFacade.class);
		return facade;
	}

}
